package cn.broadin.app.hotel.service;

import cn.broadin.app.hotel.MainActivity;
import cn.broadin.app.hotel.util.XLog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

/**
 * 监听网络状态Service
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年1月4日下午4:55:05
 */
public class ListenNetStateService extends Service {
	private ConnectivityManager connectivityManager;
	private NetworkInfo info;
	private Intent netIntent = null;
	private Bundle bundle = null;
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				Log.d("caolm:", "network status changed");
				connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				info = connectivityManager.getActiveNetworkInfo();
				if (info != null && info.isAvailable()) {
					String name = info.getTypeName();
					XLog.d("ListenNetStateService ActiveNetwork:" + name);
					sendNetworkChangedBroadcast(true);
				} else {
					XLog.d("ListenNetStateService no network");
					sendNetworkChangedBroadcast(false);
				}
			}
		}
	};

	/**
	 * 发送广播，通知UI层网络已改变
	 */
	private void sendNetworkChangedBroadcast(boolean flag) {
		bundle.putBoolean("flag", flag);
		netIntent.putExtras(bundle);
		netIntent.setAction(MainActivity.NET_CHANGED_ACTION);
		// 发送广播，通知UI层网络改变了
		sendBroadcast(netIntent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mReceiver, mFilter);
		netIntent = new Intent();
		bundle = new Bundle();
	}

	@Override
	public void onDestroy() {
		Log.d("caolm:", "service onDestroy");
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
        
		return super.onStartCommand(intent, flags, startId);
	}
}